#!/usr/bin/perl

# This script is used stop i3 servers on a set of PlanetLab nodes.
# Usage:
# stop_i3_servers.pl
#                   -d <config_directory>
#		    Contains the configuration files that were used to start the i3 servers.
#


use strict 'vars';
package main;

use Getopt::Std;
use Cwd;

use vars qw($opt_d);

require "read_deployment.pl";
my %deployment_details = &get_deployment_details;

my $deployment_binary = $deployment_details {"deployment_binary"};
my $deployment_dir = $deployment_details {"deployment_dir"};
my $deployment_username = $deployment_details {"deployment_username"};

print ("\ndeployment_binary = $deployment_binary\n");
print ("deployment_username=$deployment_username\n");
print ("deployment_dir=$deployment_dir\n");


my $ssh_options = "-o \"ConnectTimeout=20\"";

#get command line options
getopts('d:');
if ($opt_d eq "") {
    die "Usage: stop_i3servers.pl -d <conf_dir>\n";
}

chdir ($opt_d) || die "Cannot change to conf directory\n";
opendir (CONF_DIR, ".") || die "Cannot open conf directory\n";

my $filename, my @arr, my $cmd;

# Go through each .cfg file in the specificed config directory
while ($filename = readdir(CONF_DIR)) {
    
    if ($filename =~ "cfg") {
	    
        @arr = split(/_/, $filename);

        print "\n\n\n###############################################################\n";
        print "Stopping i3 on host $arr[1] at port $arr[2]\n";
	$cmd = "ssh $ssh_options $deployment_username\@$arr[1] \"cd $deployment_dir;./kill-process.pl -p $arr[2] -P $deployment_binary \"";
	system($cmd);
	
        sleep(1);
    }
}

close CONF_DIR;
